import Taro from '@tarojs/taro';
import queryString from 'query-string';
import interceptor from './interceptor';

const baseUrl = 'https://wxapi.quyizhan.com.cn';
// const baseUrl = 'https://test.quyizhan.com.cn';

interface RequestProps {
  path: string;
  query?: any;
  method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'OPTIONS';
  data?: any;
  headers?: any;
}

const request = async ({ path, query = {}, method, data, headers }: RequestProps): Promise<any> => {
  return new Promise((resolve, reject) => {
    let queryParams = {
      _v: new Date().getTime(),
      ...query,
    };
    let queryStr = queryString.stringify(queryParams);
    Taro.addInterceptor(interceptor);
    Taro.showNavigationBarLoading();
    Taro.showLoading({
      title: '请稍候...',
    });
    Taro.request({
      url: `${baseUrl}${path}?${queryStr}`,
      data: {
        ...data,
      },
      method,
      header: {
        'content-type': 'application/json', // 默认值
        ...headers,
      },
      success: function (res) {
        Taro.hideNavigationBarLoading();
        Taro.hideLoading();
        // console.log('res', res);
        if (res.statusCode === 200 || res.statusCode === 301) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: function (err) {
        Taro.hideLoading();
        Taro.hideNavigationBarLoading();
        reject(err);
      },
    });
  });
};
export const GET = (path: string, query?: any) => {
  return request({ path, query, method: 'GET' });
};
export const POST = (path: string, data?: any) => {
  return request({ path, data, method: 'POST' });
};
export const DELETE = (path: string, data?: any) => {
  return request({ path, data, method: 'DELETE' });
};
export const PUT = (path: string, data?: any) => {
  return request({ path, data, method: 'PUT' });
};

export const UPLOAD = (path: string, data?: any) => {
  return request({ path, data, method: 'POST',headers:{
    'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', // 默认值
  } });
};

export default {
  GET,
  POST,
  DELETE,
  PUT,
  UPLOAD
};
